//
//  LREmoticonManager.swift
//  WeiboX
//
//  Created by admin on 11/12/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit
import YYModel

let numOfPage = 20

class LREmoticonManager: NSObject {
	
	static let sharedManager: LREmoticonManager = LREmoticonManager()
	
	// 构造函数私有化
	private override init() {
		super.init()
	}
	
	// 创建 bundle 对象
	lazy var emoticonBundle: Bundle = {
		// bundle 路径
		let path = Bundle.main.path(forResource: "Emoticons", ofType: "bundle")!
		// 创建 bundel 对象
		let bundle = Bundle(path: path)!
		
		return bundle
	}()
	
	private lazy var recentEmoticonArr: [LREmoticon] = {
		let arr = [LREmoticon]()
		return arr
	}()
	
	private lazy var defaultEmoticonArr: [LREmoticon] = {
		return self.loadEmoticonArr(folderName: "default", fileName: "info.plist")
	}()
	
	private lazy var emojiEmoticonArr: [LREmoticon] = {
		return self.loadEmoticonArr(folderName: "emoji", fileName: "info.plist")
	}()
	
	private lazy var lxhEmoticonArr: [LREmoticon] = {
		return self.loadEmoticonArr(folderName: "lxh", fileName: "info.plist")
	}()
	
	// 个 / 页 / 组
	lazy var allEmoticonArr: [[[LREmoticon]]] = {
		return [[self.recentEmoticonArr],
		        self.sectionEmoticonArr(emoticonArr: self.defaultEmoticonArr),
		        self.sectionEmoticonArr(emoticonArr: self.emojiEmoticonArr),
		        self.sectionEmoticonArr(emoticonArr: self.lxhEmoticonArr),
		        ]
	}()
	
	// 根据表情的文件夹名和文件名读取数据
	private func loadEmoticonArr(folderName: String, fileName: String) -> [LREmoticon] {
		let subPath = folderName + "/" + fileName	// 子路径
		
		// 获得 plist 路径
		let pPath = self.emoticonBundle.path(forResource: subPath, ofType: nil)!
		// 加载 plist
		let dicArr = NSArray(contentsOfFile: pPath) as! [[String: Any]]
		// 数组转模型
		let modelArr = NSArray.yy_modelArray(with: LREmoticon.self, json: dicArr) as! [LREmoticon]
		
		for model in modelArr {
			if model.type == "0" {
				print(folderName)
				let folderPath = emoticonBundle.path(forResource: folderName, ofType: nil)!
				
				let pngName = model.png!
				
				let path = folderPath + "/" + pngName
				
				model.path = path
				model.folderName = folderName
			}
		}
		return modelArr
	}
	
	// 每组表情分页
	private func sectionEmoticonArr(emoticonArr: [LREmoticon]) -> [[LREmoticon]] {
		// 20 个/每页
		let pageCount = (emoticonArr.count + 19) / 20
		
		var tmpArr = [[LREmoticon]]()
		for i in 0 ..< pageCount {
			let loc = i * numOfPage
			var len = numOfPage
			
			if loc + len > emoticonArr.count {
				len = emoticonArr.count - loc
			}
			
			let subArr = (emoticonArr as NSArray).subarray(with: NSMakeRange(loc, len)) as! [LREmoticon]
			
			tmpArr.append(subArr)
		}
		return tmpArr
	}
}
